from bot.enterprise_wechat_gpt.util.tair_util import *


class MsgBufferUtil:
    msg_buffer_key = "QW:MsgBuffer:"

    def __init__(self):
        self.tair = TairUtil()

    def push_buffer(self, user_id, msg, thread_id):
        data = {'msg': msg, 'thread_id': thread_id}
        self.tair.lpush(MsgBufferUtil.msg_buffer_key + user_id, json.dumps(data, ensure_ascii=False))

    def pop_buffer(self, user_id):
        res = self.tair.rpop(MsgBufferUtil.msg_buffer_key + user_id)
        return json.loads(res) if res else None

    def get_buffer_top(self, user_id):
        res = self.tair.lindex(MsgBufferUtil.msg_buffer_key + user_id, 0)
        return json.loads(res) if res else None

    def join_buffer_msg(self, msg, user_id):
        buffer = self.pop_buffer(user_id)
        if buffer:
            buffer_msg = buffer.get('msg')
            if buffer_msg:
                msg = buffer_msg + ' ' + msg
                logging.info(f"userId:[{user_id}] 缓冲区有消息:{buffer_msg} 合并消息为:{msg}")
        return msg

    def join_buffer_msg_for_post(self, msg, user_id):
        buffer = self.pop_buffer(user_id)
        if buffer:
            buffer_msg = buffer.get('msg')
            if buffer_msg:
                msg = merge_msg(buffer_msg, msg)
                logging.info(f"userId:[{user_id}] 缓冲区有消息:{buffer_msg} 合并消息为:{msg}")
        return msg

    def judge_stop_handle(self, msg, user_id, thread_id):
        buffer = self.get_buffer_top(user_id)
        logging.info(f"userId:[{user_id}] buffer = {buffer}, this_msg = {msg}")
        if buffer:
            buffer_msg = buffer.get('msg')
            redis_thread_id = buffer.get('thread_id')
            if buffer_msg == msg and redis_thread_id == thread_id:
                self.pop_buffer(user_id)
                logging.info(f"userId:[{user_id}] 缓冲区的线程id和当前线程id一致, 且缓冲区的消息和当前消息一致, 输出该消息")
                return False
            else:
                logging.info(f"userId:[{user_id}] 缓冲区的消息和当前消息不一致")
                return True
        else:
            logging.info(f"userId:[{user_id}] 缓冲区没有消息")
            return True


def merge_msg(buffer_msg, msg):
    buffer_msg_list = buffer_msg.split(',')
    msg_list = msg.split(',')
    # 使用set集合记录已经添加过的子字符串，并按原始顺序合并
    seen = set()
    merged_list = []
    for segment in buffer_msg_list + msg_list:
        if segment not in seen:
            merged_list.append(segment)
            seen.add(segment)
    # 使用逗号连接合并后的片段
    msg = ','.join(merged_list)
    return msg


msg_buffer_util = MsgBufferUtil()

if __name__ == '__main__':
    msg_buffer_util = MsgBufferUtil()
    msg_buffer_util.push_buffer("123", '不是', 4900)
    res = msg_buffer_util.get_buffer_top("123")
    print(res)
